package com.mwx.loseweight.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mwx.loseweight.mapper.UserMapper;
import com.mwx.loseweight.pojo.dto.UserPageDTO;
import com.mwx.loseweight.pojo.entity.User;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;


    public void save(User user) {
        String md5Password = DigestUtils.md5Hex(user.getPassword());
        user.setPassword(md5Password);
        userMapper.insert(user);
    }

    public void delete(User user) {
        userMapper.deleteById(user.getId());
    }

    public void update(User user) {
        if (user.getPassword() != null) {
            user.setPassword(DigestUtils.md5Hex(user.getPassword())); //把密码修改的密码进行md5加密
        }
        userMapper.updateById(user);
    }

    public User get(User user) {
        return userMapper.selectById(user.getId());
    }

    public Page<User> list(UserPageDTO userPageDTO) {

        Page<User> page = new Page<>(userPageDTO.getPage(), userPageDTO.getPageSize());
        //下一条sql进行分页，自动加入limit关键字分页
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("is_admin", 0, 2);
        if (userPageDTO.getUsername() != null) {
            queryWrapper.like("username", userPageDTO.getUsername());
        }
        return userMapper.selectPage(page, queryWrapper);
    }

    public User findByUserName(String username) {
        return userMapper.selectOne(new QueryWrapper<User>().eq("username", username));
    }
}
